package com.yikaiye.android.yikaiye.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.application.MyApplication;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.DialogOrderBinding;
import com.yikaiye.android.yikaiye.http.ApiFactory;
import com.yikaiye.android.yikaiye.http.HttpRespond;
import com.yikaiye.android.yikaiye.http.MyObserver;
import com.yikaiye.android.yikaiye.http.RetrofitHelper;
import com.yikaiye.android.yikaiye.model.OrderProductModel;
import com.yikaiye.android.yikaiye.ui.activity.order.OrderDetailsActivity;
import com.yikaiye.android.yikaiye.utils.CommonUtil;
import com.yikaiye.android.yikaiye.utils.DateUtil;
import com.yikaiye.android.yikaiye.utils.JumpIntent;
import com.yikaiye.android.yikaiye.utils.ToastHelper;
import com.yikaiye.android.yikaiye.utils.UMengUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 预订单弹窗
 */
public class OrderDialog {
    private final Dialog dialog;
    private CountDownTimer countDownTimer;

    public OrderDialog(Context context, OrderProductModel orderProductModel) {
        UMengUtil.setCountEventId(Constant.DIALOG_PRE_ORDER);
        DialogOrderBinding binding = DialogOrderBinding.inflate(LayoutInflater.from(context));
        dialog = new Dialog(context, R.style.prompt_progress_dialog_dimenabled);
        dialog.setContentView(binding.getRoot(), new LinearLayout.LayoutParams
                (LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        dialog.setCancelable(false);
        Window dialogWindow = dialog.getWindow();
        if (dialogWindow != null) {
            // 去除遮罩效果
//        dialogWindow.setDimAmount(0f);
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            dialogWindow.setGravity(Gravity.BOTTOM);
            dialogWindow.setWindowAnimations(R.style.main_menu_animStyle);
            // lp.x = 266; // 新位置X坐标
            // lp.y = Utils.dip2px(activity, 300); // 新位置Y坐标
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            dialogWindow.setAttributes(lp);
        }

        binding.tvTitle.setText(CommonUtil.checkText(orderProductModel.getProductName()));
        binding.tvPrice.setText(context.getString(R.string.price, orderProductModel.getPrice()));
        binding.tvDes.setText(CommonUtil.checkText(orderProductModel.getSlogan()));
        Glide.with(MyApplication.getContext()).
                load(ApiFactory.BASE_IMAGE_URL + orderProductModel.getAppBanner())
                .placeholder(R.mipmap.default_image).error(R.mipmap.default_image).into(binding.ivProductImg);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            long countdownTime = df.parse(orderProductModel.getExpirationTime()).getTime() - new Date().getTime();
            countDownTimer = new CountDownTimer(countdownTime, 1000) {
                @SuppressLint("SetTextI18n")
                public void onTick(long millisUntilFinished) {
                    binding.tvPayTime.setText(context.getString(R.string.wait_pay_time, DateUtil.getTime(millisUntilFinished)));
                }

                public void onFinish() {

                }
            };
            countDownTimer.start();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        binding.tvCancel.setOnClickListener(v -> {
            if (!CommonUtil.isCanClick()) return;
            UMengUtil.setCountEventId(Constant.DIALOG_PRE_ORDER_CANCEL);
            RetrofitHelper.getInstance().execute(RetrofitHelper.getService().cancelPreOrder(orderProductModel.getId()), new MyObserver<HttpRespond<String>>() {
                @Override
                protected void onSuccess(HttpRespond<String> httpRespond) {
                    if (Constant.SUCCESS == httpRespond.code) {
                        if (null != countDownTimer) {
                            countDownTimer.cancel();
                        }
                    } else {
                        ToastHelper.show(httpRespond.msg);
                    }
                    dismissDialog();
                }

                @Override
                protected void onFail(Throwable e) {
                }
            });
        });
        binding.tvPay.setOnClickListener(v -> {
            UMengUtil.setCountEventId(Constant.DIALOG_PRE_ORDER_PAY);
            countDownTimer.cancel();
            Bundle bundle = new Bundle();
            bundle.putString(Constant.ID_KEY, orderProductModel.getId());
            JumpIntent.jump((Activity) context, OrderDetailsActivity.class, bundle);
        });
    }

    public void showDialog() {
        dialog.show();
    }

    public void dismissDialog() {
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }

    public boolean isShow() {
        return dialog.isShowing();
    }
}
